#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <mswsock.h>

// 取消定义可能冲突的宏
#ifdef X509_NAME
#undef X509_NAME
#endif

#ifdef OCSP_RESPONSE
#undef OCSP_RESPONSE
#endif

#ifdef X509_EXTENSIONS
#undef X509_EXTENSIONS
#endif

#ifdef PKCS7_SIGNER_INFO
#undef PKCS7_SIGNER_INFO
#endif

#ifdef SKM_DEFINE_STACK_OF_INTERNAL
#undef SKM_DEFINE_STACK_OF_INTERNAL
#endif


#include <openssl/ssl.h>
#include <openssl/err.h>
#include <ioapiset.h>


#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "kernel32.lib")
#pragma comment(lib, "libssl.lib") // 需要链接 OpenSSL 库
#pragma comment(lib, "libcrypto.lib")


#define MAX_HANDLERS 1024
#define COMPLETION_KEY_LISTEN 1
#define COMPLETION_KEY_CLIENT 2

#define CLIENT_HTTPS_PORT 443
#define TARGET_HOST "127.0.0.1" // 替换为你的目标主机
#define TARGET_HTTP_PORT 8080

#define SERVER_CERT_FILE "d:/cpp/reverseproxy/certs/server/server.crt" // 替换为你的证书路径
#define SERVER_KEY_FILE "d:/cpp/reverseproxy/certs/server/server.key"   // 替换为你的私钥路径


// 自定义 OVERLAPPED 结构体，包含用户数据
typedef struct overlapped_ex_s {
    OVERLAPPED overlapped;
    SOCKET client_socket; // 原始客户端套接字 Client socket
    SOCKET target_socket; // 后端服务器套接字 Backend server socket
    char buffer[1024];
    int bytes_read;
    int operation_type; // 可以用于区分读写等操作 FD_READ, FD_ACCEPT, etc.
    SSL *ssl; // 用于存储 SSL 上下文 SSL context
    void *arg; // 用户自定义参数 User-defined argument (e.g., loop pointer)
    void (*callback)(SOCKET, int, void *); // Callback function
} overlapped_ex_t;

// 事件处理器结构体 (不再直接存储在数组中)
typedef struct event_handler_s {
    SOCKET fd;
    void (*callback)(SOCKET, int, void *); // 事件发生时的回调函数
    void *arg;           // 用户自定义参数
} event_handler_t;

// 事件库上下文
typedef struct event_loop_s {
    HANDLE completion_port;
    // 可以使用哈希表或其他数据结构来管理 SOCKET 和 event_handler_t 的映射
    HANDLE handler_map_mutex;
    HANDLE handler_map; // 简单的数组模拟映射，实际应用中应使用更高效的数据结构
    int handler_count;
    SSL_CTX *ssl_ctx; // SSL 上下文
} event_loop_t;

// 前置声明
void on_client_read(SOCKET fd, int events, void *arg);
void on_target_read(SOCKET fd, int events, void *arg);
void handle_proxy(SOCKET client_socket, BOOL is_ssl, SSL *ssl, event_loop_t *loop);
void event_loop_destroy(event_loop_t *loop);
int event_add(event_loop_t *loop, SOCKET fd, int events, void (*callback)(SOCKET, int, void *), void *arg);
void event_loop(event_loop_t *loop);
event_loop_t *event_loop_create();
void cleanup_ol(overlapped_ex_t *ol);

// 初始化 OpenSSL
int init_openssl() {
    SSL_library_init();
    OpenSSL_add_all_algorithms();
    SSL_load_error_strings();
    return 0;
}

// 创建 SSL 上下文
SSL_CTX *create_ssl_context() {
    const SSL_METHOD *method;
    SSL_CTX *ctx;

    method = TLS_server_method();
    ctx = SSL_CTX_new(method);
    if (!ctx) {
        perror("SSL_CTX_new failed");
        ERR_print_errors_fp(stderr);
        return NULL;
    }

    if (SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM) <= 0) {
        perror("SSL_CTX_use_certificate_file failed");
        ERR_print_errors_fp(stderr);
        SSL_CTX_free(ctx);
        return NULL;
    }

    if (SSL_CTX_use_PrivateKey_file(ctx, SERVER_KEY_FILE, SSL_FILETYPE_PEM) <= 0) {
        perror("SSL_CTX_use_PrivateKey_file failed");
        ERR_print_errors_fp(stderr);
        SSL_CTX_free(ctx);
        return NULL;
    }

    return ctx;
}

// 初始化事件库
event_loop_t *event_loop_create() {
    event_loop_t *loop = (event_loop_t *)malloc(sizeof(event_loop_t));
    if (!loop) {
        perror("malloc failed");
        return NULL;
    }
    loop->completion_port = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
    loop->handler_map_mutex = CreateMutex(NULL, FALSE, NULL);
    loop->handler_map = calloc(MAX_HANDLERS, sizeof(event_handler_t));
    loop->handler_count = 0;
    loop->ssl_ctx = create_ssl_context();
    if (loop->completion_port == NULL || !loop->handler_map_mutex || !loop->ssl_ctx) {
        perror("CreateIoCompletionPort failed");
        free(loop->handler_map);
        if (loop->ssl_ctx) SSL_CTX_free(loop->ssl_ctx);
        free(loop);
        return NULL;
    }

    return loop;
}

// 注册事件处理器 (将 SOCKET 关联到完成端口)
int event_add(event_loop_t *loop, SOCKET fd, int events, void (*callback)(SOCKET, int, void *), void *arg) {
    if (!loop || fd == INVALID_SOCKET || !callback) {
        errno = EINVAL;
        perror("event_add: invalid arguments");
        return -1;
    }

    // Check if socket is valid
    int optval;
    int optlen = sizeof(optval);
    if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (char*)&optval, &optlen) == SOCKET_ERROR) {
        perror("event_add: invalid socket");
        return -1;
    }

    HANDLE result = CreateIoCompletionPort((HANDLE)fd, loop->completion_port, (ULONG_PTR)fd, 0);
    if (result == NULL) {
        DWORD lastError = GetLastError();
        fprintf(stderr, "CreateIoCompletionPort failed with error %ld\n", lastError);

        // if (lastError != ERROR_SUCCESS) {
        //     perror("CreateIoCompletionPort (associate socket) failed");
        //     return -1;
        // }
        // 如果 GetLastError() 是 ERROR_SUCCESS，则不应该认为关联失败
        // 但这通常不应该发生，CreateIoCompletionPort 失败时会设置错误码
        // fprintf(stderr, "Warning: CreateIoCompletionPort returned NULL with no error.\n");
        return -1;
    }

    WaitForSingleObject(loop->handler_map_mutex, INFINITE);
    if (loop->handler_count < MAX_HANDLERS) {
        event_handler_t *handler = ((event_handler_t *)loop->handler_map) + loop->handler_count++;
        handler->fd = fd;
        handler->callback = callback;
        handler->arg = arg;
    } else {
        ReleaseMutex(loop->handler_map_mutex);
        fprintf(stderr, "event_add: max handlers reached\n");
        return -1;
    }
    ReleaseMutex(loop->handler_map_mutex);

    // 对于监听 socket，需要立即投递一个 AcceptEx 操作
    if (events & FD_ACCEPT) {
        SOCKET accept_socket = socket(AF_INET, SOCK_STREAM, 0);
        if (accept_socket == INVALID_SOCKET) {
            perror("socket (accept) failed");
            return -1;
        }
        overlapped_ex_t *ol = (overlapped_ex_t *)malloc(sizeof(overlapped_ex_t) + (sizeof(SOCKADDR_IN) + 16) * 2); // AcceptEx 需要额外的缓冲区
        memset(ol, 0, sizeof(*ol));
        ol->client_socket = fd; // 监听 socket
        ol->operation_type = FD_ACCEPT;
        ol->arg = loop; // 传递 loop 指针
        ol->buffer[0] = 0; // 占位符

        BOOL success = AcceptEx(fd, accept_socket, ol->buffer, 0, sizeof(SOCKADDR_IN) + 16, sizeof(SOCKADDR_IN) + 16, NULL, &ol->overlapped);
        if (!success && WSAGetLastError() != WSA_IO_PENDING) {
            perror("AcceptEx failed");
            closesocket(accept_socket);
            free(ol);
            return -1;
        }
        // 新的 accept_socket 会在 GetQueuedCompletionStatus 中返回
    }
    // 对于其他 socket (读/写)，通常在连接建立后投递 ReadFile/WriteFile (WSARecv/WSASend) 操作
    else if (events & FD_READ) {
        overlapped_ex_t *ol = (overlapped_ex_t *)malloc(sizeof(overlapped_ex_t));
        memset(ol, 0, sizeof(*ol));
        ol->client_socket = fd;
        ol->operation_type = FD_READ;
        ol->arg = arg; // 将用户提供的 arg 存储到 ol->arg 中
        ol->callback = callback; // Store callback
        ol->ssl = NULL; // 初始为 NULL
        // 判断是否是 SSL 连接（这里假设 arg 中可能包含这个信息，或者根据监听端口判断）
        BOOL is_ssl_conn = FALSE;
        WaitForSingleObject(loop->handler_map_mutex, INFINITE);
        for (int i = 0; i < loop->handler_count; ++i) {
            event_handler_t *handler = ((event_handler_t *)loop->handler_map) + i;
            if (handler->fd == fd) {
                SOCKADDR_IN local_addr;
                int local_addr_len = sizeof(local_addr);
                if (getsockname(fd, (SOCKADDR *)&local_addr, &local_addr_len) == 0) {
                    is_ssl_conn = (ntohs(local_addr.sin_port) == CLIENT_HTTPS_PORT);
                }
                break;
            }
        }
        ReleaseMutex(loop->handler_map_mutex);
        printf("is_ssl_conn:%s", is_ssl_conn ? "true" : "false");
        ol->ssl = is_ssl_conn ? SSL_new(loop->ssl_ctx) : NULL;
        if (is_ssl_conn && ol->ssl) {
            if (SSL_set_fd(ol->ssl, fd) <= 0 || SSL_accept(ol->ssl) <= 0) {
                ERR_print_errors_fp(stderr);
                SSL_free(ol->ssl);
                free(ol);
                closesocket(fd);
                return -1;
            }
            // Initial SSL_read will be done in handle_proxy
        } else {
            BOOL success = WSARecv(fd, (LPWSABUF)&ol->buffer, 1, NULL, NULL, &ol->overlapped, NULL);
            if (!success && WSAGetLastError() != WSA_IO_PENDING) {
                perror("WSARecv failed");
                if (ol->ssl) SSL_free(ol->ssl);
                free(ol);
                return -1;
            }
        }
    }

    return 0;
}

// 删除事件处理器 (需要关闭套接字)
int event_del(event_loop_t *loop, SOCKET fd) {
    // 需要查找并清理 overlapped 结构体
    WaitForSingleObject(loop->handler_map_mutex, INFINITE);
    for (int i = 0; i < loop->handler_count; ++i) {
        event_handler_t *handler = ((event_handler_t *)loop->handler_map) + i;
        if (handler->fd == fd) {
            // 可以标记为无效或移动最后一个元素来移除
            memset(handler, 0, sizeof(*handler));
            // 简单起见，这里不立即调整 handler_count
            break;
        }
    }
    ReleaseMutex(loop->handler_map_mutex);
    closesocket(fd);
    // 需要从 handler_map 中移除，这里省略具体实现
    return 0;
}

// 事件循环
void event_loop(event_loop_t *loop) {
    if (!loop) {
        fprintf(stderr, "event_loop: invalid loop\n");
        return;
    }

    DWORD bytes_transferred;
    ULONG_PTR completion_key;
    LPOVERLAPPED lp_overlapped;
    BOOL result;

    while (1) {
        result = GetQueuedCompletionStatus(
            loop->completion_port,
            &bytes_transferred,
            &completion_key,
            &lp_overlapped,
            INFINITE // 可以设置超时
        );

        if (lp_overlapped != NULL) {
            overlapped_ex_t *ol = (overlapped_ex_t *)lp_overlapped;
            SOCKET fd = ol->client_socket;
            int events = 0;

            if (result == FALSE && GetLastError() != ERROR_IO_PENDING) {
                // 处理错误，例如连接断开
                fprintf(stderr, "GetQueuedCompletionStatus error on socket %lld: %d\n", (long long)fd, GetLastError());
                events |= FD_CLOSE;
            } else {
                if (ol->operation_type == FD_ACCEPT) {
                    events |= FD_ACCEPT;
                    // SOCKET accept_socket = ol->buffer[0]; // 临时存储了 accept socket
                    SOCKET accept_socket = socket(AF_INET, SOCK_STREAM, 0); // Create new socket for next AcceptEx
                    if (accept_socket == INVALID_SOCKET) {
                        perror("socket (accept) failed");
                        free(ol);
                        continue;
                    }

                    // 需要获取客户端地址信息并进行进一步处理
                    SOCKADDR_IN client_addr, local_addr;
                    int client_addr_len = sizeof(client_addr);
                    int local_addr_len = sizeof(local_addr);
                    GetAcceptExSockaddrs(ol->buffer, 0, sizeof(SOCKADDR_IN) + 16, sizeof(SOCKADDR_IN) + 16,
                                         (SOCKADDR **)&local_addr, &local_addr_len,
                                         (SOCKADDR **)&client_addr, &client_addr_len);
                    printf("Accepted connection from %s:%d on socket %lld\n",
                           inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), (long long)ol->client_socket);

                    // 判断是否是 HTTPS 连接 (这里假设监听 HTTPS_PORT 的连接都是 HTTPS)
                    BOOL is_ssl = (ntohs(local_addr.sin_port) == CLIENT_HTTPS_PORT);
                    // BOOL is_ssl = (ntohs(((SOCKADDR_IN *)&local_addr)->sin_port) == CLIENT_HTTPS_PORT);
                    SSL *ssl = NULL;
                    if (is_ssl && loop->ssl_ctx) {
                        ssl = SSL_new(loop->ssl_ctx);
                        if (ssl) {
                            if (SSL_set_fd(ssl, ol->client_socket) <= 0 || SSL_accept(ssl) <= 0) {
                                ERR_print_errors_fp(stderr);
                                SSL_free(ssl);
                                ssl = NULL;
                                is_ssl = FALSE;
                            }
                        } else {
                            is_ssl = FALSE;
                        }
                    }

                    if (CreateIoCompletionPort((HANDLE)ol->client_socket, loop->completion_port, (ULONG_PTR)ol->client_socket, 0) == NULL) {
                        fprintf(stderr, "CreateIoCompletionPort for accepted socket failed: %ld\n", GetLastError());
                        if (ssl) SSL_free(ssl);
                        closesocket(ol->client_socket);
                        free(ol);
                        continue;
                    }

                    // 启动代理处理
                    handle_proxy(ol->client_socket, is_ssl, ssl, loop); // 传递 loop 指针

                    // Post another AcceptEx
                    overlapped_ex_t *new_ol = (overlapped_ex_t *)malloc(sizeof(overlapped_ex_t) + (sizeof(SOCKADDR_IN) + 16) * 2);
                    memset(new_ol, 0, sizeof(*new_ol));
                    new_ol->client_socket = fd; // Listening socket
                    new_ol->operation_type = FD_ACCEPT;
                    new_ol->arg = loop;
                    BOOL success = AcceptEx(fd, accept_socket, new_ol->buffer, 0, sizeof(SOCKADDR_IN) + 16, sizeof(SOCKADDR_IN) + 16, NULL, &new_ol->overlapped);
                    if (!success && WSAGetLastError() != WSA_IO_PENDING) {
                        perror("AcceptEx (again) failed");
                        closesocket(accept_socket);
                        free(new_ol);
                    }

                    free(ol); // Free the original overlapped structure
                    // 再次投递 AcceptEx
                    // SOCKET new_accept_socket = socket(AF_INET, SOCK_STREAM, 0);
                    // if (new_accept_socket != INVALID_SOCKET) {
                    //     memset(ol, 0, sizeof(*ol));
                    //     ol->client_socket = fd;
                    //     ol->operation_type = FD_ACCEPT;
                    //     ol->arg = loop; // 传递 loop 指针
                    //     BOOL success = AcceptEx(fd, new_accept_socket, ol->buffer, 0, sizeof(SOCKADDR_IN) + 16, sizeof(SOCKADDR_IN) + 16, NULL, &ol->overlapped);
                    //     if (!success && WSAGetLastError() != WSA_IO_PENDING) {
                    //         perror("AcceptEx (again) failed");
                    //         closesocket(new_accept_socket);
                    //         free(ol);
                    //     }
                    // } else {
                    //     perror("socket (accept again) failed");
                    //     free(ol);
                    // }
                    // closesocket(accept_socket); // Close the accepted socket here, handle_proxy gets its own
                } else if (ol->callback) {
                    ol->bytes_read = bytes_transferred;
                    ol->callback(fd, FD_READ, ol);
                }
            }
            if (events & FD_CLOSE && ol->callback) {
                ol->callback(fd, FD_CLOSE, ol);
            }
        }
    }
}

// 销毁事件循环
void event_loop_destroy(event_loop_t *loop) {
    if (loop) {
        CloseHandle(loop->completion_port);
        CloseHandle(loop->handler_map_mutex);
        free(loop->handler_map);
        if (loop->ssl_ctx) {
            SSL_CTX_free(loop->ssl_ctx);
        }
        free(loop);
    }
}
// 示例回调函数：处理新连接 (IOCP 中通常在事件循环中处理 AcceptEx 完成)
void on_accept(SOCKET fd, int events, void *arg) {
    printf("ON_Accept...\n");
    // IOCP 的 accept 通常在事件循环中处理 AcceptEx 的完成事件
    // 这里可能不需要额外的回调，或者用于连接建立后的进一步处理
}
void on_client_read(SOCKET fd, int events, void *arg) {
    overlapped_ex_t *ol = (overlapped_ex_t *)arg;
    event_loop_t *loop = (event_loop_t *)ol->arg;
    SOCKET target_socket = *(SOCKET *)ol->buffer; // Retrieve target_socket from buffer

    if (events & FD_READ) {
        printf("Read %d bytes from target fd %lld\n", ol->bytes_read, (long long)fd);
        // Forward data to target server
        int bytes;
        if (ol->ssl) {
            bytes = SSL_read(ol->ssl, ol->buffer, sizeof(ol->buffer));
            if (bytes <= 0) {
                int ssl_err = SSL_get_error(ol->ssl, bytes);
                if (ssl_err == SSL_ERROR_WANT_READ) {
                    WSARecv(fd, &(WSABUF){ .buf = ol->buffer, .len = sizeof(ol->buffer) }, 1, NULL, NULL, &ol->overlapped, NULL);
                    return;
                }
                closesocket(fd);
                closesocket(ol->target_socket);
                SSL_free(ol->ssl);
                free(ol);
                return;
            }
        } else {
            bytes = ol->bytes_read;
        }

        int sent = send(ol->target_socket, ol->buffer, bytes, 0);
        if (sent == SOCKET_ERROR) {
            closesocket(fd);
            closesocket(ol->target_socket);
            if (ol->ssl) SSL_free(ol->ssl);
            free(ol);
            return;
        }

        printf("Forwarded %d bytes to target fd %lld\n", sent, (long long)target_socket);

        // Prepare to read response from target
        overlapped_ex_t *target_ol = calloc(1, sizeof(overlapped_ex_t));
        target_ol->client_socket = fd;
        target_ol->target_socket = ol->target_socket;
        target_ol->operation_type = FD_READ;
        target_ol->ssl = ol->ssl; // Pass client SSL context
        target_ol->arg = loop; // Pass loop for event_add
        // BOOL success = WSARecv(target_socket, (LPWSABUF)&target_ol->buffer, 1, NULL, NULL, &target_ol->overlapped, NULL);
        WSARecv(ol->target_socket, &(WSABUF){ .buf = target_ol->buffer, .len = sizeof(target_ol->buffer) }, 1, NULL, NULL, &target_ol->overlapped, NULL);
        event_add(loop, ol->target_socket, FD_READ, on_target_read, target_ol);
        memset(&ol->overlapped, 0, sizeof(ol->overlapped));
        WSARecv(fd, &(WSABUF){ .buf = ol->buffer, .len = sizeof(ol->buffer) }, 1, NULL, NULL, &ol->overlapped, NULL);
    } else if (events & FD_CLOSE) {
        printf("Connection closed on client fd %lld\n", (long long)fd);
        closesocket(fd);
        closesocket(ol->target_socket);
        if (ol->ssl) SSL_free(ol->ssl);
        free(ol);
    }
}

void on_target_read(SOCKET fd, int events, void *arg) {
    overlapped_ex_t *ol = (overlapped_ex_t *)arg;
    event_loop_t *loop = (event_loop_t *)((overlapped_ex_t *)ol)->arg;

    if (events & FD_READ) {
        printf("Read %d bytes from target fd %lld\n", ol->bytes_read, (long long)fd);
        int bytes = ol->bytes_read;
        int sent = ol->ssl ? SSL_write(ol->ssl, ol->buffer, bytes) : send(ol->client_socket, ol->buffer, bytes, 0);
        if (sent <= 0 && ol->ssl) {
            int ssl_err = SSL_get_error(ol->ssl, sent);
            if (ssl_err == SSL_ERROR_WANT_WRITE) {
                // Handle write retry
                printf("SSL_ERROR_WANT_WRITE.\n");
                return;
            }
        }
        if (sent == SOCKET_ERROR || (ol->ssl && sent <= 0)) {
            closesocket(ol->client_socket);
            closesocket(fd);
            if (ol->ssl) SSL_free(ol->ssl);
            free(ol);
            return;
        }

        memset(&ol->overlapped, 0, sizeof(ol->overlapped));
        WSARecv(fd, &(WSABUF){ .buf = ol->buffer, .len = sizeof(ol->buffer) }, 1, NULL, NULL, &ol->overlapped, NULL);
    } else if (events & FD_CLOSE) {
        printf("Connection closed on target fd %lld\n", (long long)fd);
        closesocket(ol->client_socket);
        closesocket(fd);
        if (ol->ssl) SSL_free(ol->ssl);
        free(ol);
    }
}

// 处理代理逻辑 (目前仅为框架)
void handle_proxy(SOCKET client_socket, BOOL is_ssl, SSL *ssl, event_loop_t *loop) {
    printf("Handling proxy for socket %lld (SSL: %s)\n", (long long)client_socket, is_ssl ? "yes" : "no");

    overlapped_ex_t *ol = calloc(1, sizeof(overlapped_ex_t));
    ol->client_socket = client_socket;
    ol->operation_type = FD_READ;
    ol->arg = loop;
    ol->ssl = ssl;

    SOCKET target_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (target_socket == INVALID_SOCKET) {
        perror("socket (target) failed");
        if (ssl) {
            SSL_shutdown(ssl);
            SSL_free(ssl);
        }
        closesocket(client_socket);
        free(ol);
        return;
    }

    struct sockaddr_in target_addr = { .sin_family = AF_INET, .sin_port = htons(TARGET_HTTP_PORT) };
    inet_pton(AF_INET, TARGET_HOST, &target_addr.sin_addr);
    
    if (connect(target_socket, (struct sockaddr*)&target_addr, sizeof(target_addr)) == SOCKET_ERROR) {
        perror("connect to target failed");
        cleanup_ol(ol);
        return;
    }
    printf("Connected to target server %s:%d\n", TARGET_HOST, TARGET_HTTP_PORT);
    ol->target_socket = target_socket;
    SSL_set_mode(ssl, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
    event_add(loop, client_socket, FD_READ, on_client_read, ol);
}

void cleanup_ol(overlapped_ex_t *ol) {
    if (ol->ssl) {
        SSL_shutdown(ol->ssl);
        SSL_free(ol->ssl);
    }
    if (ol->client_socket != INVALID_SOCKET) {
        closesocket(ol->client_socket);
        ol->client_socket = INVALID_SOCKET;
    }
    if (ol->target_socket != INVALID_SOCKET) {
        closesocket(ol->target_socket);
        ol->target_socket = INVALID_SOCKET;
    }
    free(ol);
}

int main() {
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        fprintf(stderr, "WSAStartup failed\n");
        return 1;
    }

    // 初始化 OpenSSL
    init_openssl();
    SSL_CTX *ssl_ctx = create_ssl_context();
    if (!ssl_ctx) {
        WSACleanup();
        return 1;
    }
    SSL_load_error_strings();

    event_loop_t *loop = event_loop_create();
    if (!loop) {
        SSL_CTX_free(ssl_ctx);
        WSACleanup();
        return 1;
    }
    loop->ssl_ctx = ssl_ctx;
    
    SOCKET client_socket_https = socket(AF_INET, SOCK_STREAM, 0);
    if (client_socket_https == INVALID_SOCKET) {
        perror("socket (HTTPS) failed");
        closesocket(client_socket_https);
        event_loop_destroy(loop);
        WSACleanup();
        return 1;
    }

    // struct sockaddr_in addr = { .sin_family = AF_INET, .sin_addr.s_addr = INADDR_ANY, .sin_port = htons(CLIENT_HTTPS_PORT) };
    struct sockaddr_in addr = { .sin_family = AF_INET, .sin_port = htons(CLIENT_HTTPS_PORT) };
    if (inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr) <= 0) {
        fprintf(stderr, "inet_pton failed: %ld\n", WSAGetLastError());
        closesocket(client_socket_https);
        event_loop_destroy(loop);
        WSACleanup();
        return 1;
    }
    if (bind(client_socket_https, (SOCKADDR *)&addr, sizeof(addr)) == SOCKET_ERROR) {
        fprintf(stderr, "bind (HTTPS) failed: %ld\n", WSAGetLastError());
        closesocket(client_socket_https);
        event_loop_destroy(loop);
        WSACleanup();
        return 1;
    }

    if (listen(client_socket_https, SOMAXCONN) == SOCKET_ERROR) {
        perror("listen (HTTPS) failed");
        closesocket(client_socket_https);
        event_loop_destroy(loop);
        WSACleanup();
        return 1;
    }
    printf("Listening for HTTPS on port %d\n", CLIENT_HTTPS_PORT);
    event_add(loop, client_socket_https, FD_ACCEPT, on_accept, loop);

    event_loop(loop);

    closesocket(client_socket_https);
    event_loop_destroy(loop);
    WSACleanup();

    return 0;
}